package ulez.messagerdemo;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

/**
 * android:process=":remote"，不在同一个进程；
 */
public class MessengerService extends Service {
    private static final String TAG = "MessengerService";

    private final Messenger mMessenger =new Messenger(new MessengerHandler());
    class MessengerHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MyConstants.MSG_FROM_CLIENT:
                    Bundle data = msg.getData();
                    String s = data.getString("msg");
                    Log.e(TAG, s);
//以上是接受消息，下面是回复消息；
                    Messenger client=msg.replyTo;
                    Message replyMessage=Message.obtain(null,MyConstants.MSG_FROM_SERVICE);
                    Bundle bundle=new Bundle();
                    bundle.putString("reply","reply message ==i have received message ,later reply to you.");
                    replyMessage.setData(bundle);
                    try {
                        client.send(replyMessage);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }

                    break;
            }
        }
    }

    public MessengerService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }
}
